import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

df = pd.read_excel(r"C:\Users\Administrator\PycharmProjects\PythonProject1\data\bwic.xlsx")
pd.set_option('display.max_columns', 100)
cusip_time = df[df['cusip'] == df['cusip'][6]][['market_price', 'created_time']]
cusip_time.reset_index(drop=True, inplace=True)
cusip_time.created_time = cusip_time.created_time.astype(str)

# Get the Peaks and Troughs *diff, sign
data = cusip_time['market_price'].values
double_diff = np.diff(np.sign(np.diff(data)))
peak_locations = np.where(double_diff == -2)[0] + 1
double_diff2 = np.diff(np.sign(np.diff(-1 * data)))
trough_locations = np.where(double_diff2 == -2)[0] + 1

# Draw Plot
plt.figure(figsize=(16, 10), dpi=80)
plt.plot('created_time', 'market_price', data=cusip_time, color='tab:blue', label='Trade Price')
plt.scatter(cusip_time.created_time[peak_locations], cusip_time.market_price[peak_locations],
            marker=mpl.markers.CARETUPBASE, color='tab:green', s=100, label='Peaks')
plt.scatter(cusip_time.created_time[trough_locations], cusip_time.market_price[trough_locations],
            marker=mpl.markers.CARETDOWNBASE, color='tab:red', s=100, label='Troughs')
# Annotate
for t, p in zip(trough_locations[1::20], peak_locations[::20]):
    plt.text(cusip_time.created_time[p], cusip_time.market_price[p] + 0.5, cusip_time.created_time[p][-4:],
             horizontalalignment='center', color='darkgreen')
    plt.text(cusip_time.created_time[t], cusip_time.market_price[t] - 0.5, cusip_time.created_time[t][-4:],
             horizontalalignment='center', color='darkred')

# Decoration
# plt.ylim(10, 30)
xtick_location = cusip_time.index.tolist()[::20]
xtick_labels = cusip_time.created_time.tolist()[::20]
plt.xticks(ticks=xtick_location, labels=xtick_labels, rotation=90, fontsize=12, alpha=.7)
plt.title("Peak and Troughs of Trade Price", fontsize=22)
plt.yticks(fontsize=12, alpha=.7)
# Lighten borders
plt.gca().spines["top"].set_alpha(.0)
plt.gca().spines["bottom"].set_alpha(.3)
plt.gca().spines["right"].set_alpha(.0)
plt.gca().spines["left"].set_alpha(.3)
plt.legend(loc='upper left')
plt.grid(axis='y', alpha=.3)
plt.show()